/*
 * @Author: your name
 * @Date: 2020-10-28 18:40:07
 * @LastEditTime: 2020-10-29 05:04:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bc-guess-up-down-h5\src\utils\request.js
 */
import Vue from 'vue'
import axios from 'axios'
import {
    Toast
} from 'vant';
let vm = new Vue()


import {getToken, getAllToken, removeAllToken} from '@/utils/auth'

// create an axios instance
const service = axios.create({
	//baseURL: process.env.BASE_API, // api的base_url
	baseURL: '', // api的base_url
	headers: {
		'Content-Type': 'application/json'
	},
	timeout: 1000*60*10 // request timeout
})

const sourceUrl = {
	"index":'/bc-guess-up-down/home',  //猜涨跌首页
	"indexSlider":'/bc-prize-customer/banner/show', //中间广告位
	"indexType":'/bc-prize-customer/product/show', //分类商品
	"productDetail":'/bc-prize-customer/product/detail', //商品详情
	'cartList':'/bc-prize-shopping-cart/shopping/cart/getCartList',//购物车列表
	'pay':'/bc-prize-pay/bc-prize-pay/v1/pay',//去支付
	'like':'/bc-prize-customer/product/guess/like',//猜你喜欢
	'buyNow':'/bc-prize-pay/buy/now',//猜你喜欢
	'accounts':'/bc-prize-pay/settle/accounts',//猜你喜欢
}
// let api = "/dpi/bc-prize-customer"
// let cpi = "/dpi/bc-prize-shopping-cart"
// let dpi = "/dpi/bc-prize-marketing"
// let epi = "/dpi/bc-prize-pay"
// request interceptor
service.interceptors.request.use(
	config => {
		config.headers['Content-Type'] = 'application/json';
		config.headers['CHANNEL_NO'] = '1fa72678b069024789d5f555b0ad70f7';
		
		// Do something before request is sent
		if (getAllToken("accessToken")) {
			// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
			config.headers['accessToken'] =  getAllToken("accessToken");
		}
		if (getAllToken("SOURCE_URI")) {
			// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
			config.headers['SOURCE_URI'] =  sourceUrl[getAllToken("SOURCE_URI")];
		}
		return config
	},
	error => {
		// Do something with request error
		// console.log(error) // for debug
	}
)

// respone interceptor
service.interceptors.response.use(
	// response => response,
	/**
	 * 下面的注释为通过在response里，自定义code来标示请求状态
	 * 当code返回如下情况则说明权限有问题，登出并返回到登录页
	 * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
	 * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
	 */
	response => {
		// console.log(res,'有响应')
		const res = response.data;
		removeAllToken("SOURCE_URI")
		// console.log(response,'response.status')
		if (response.status !== 200) {
			Toast('request 请求错误，')
			// vm.$vux.toast.show({
			// 	width:"5rem",
			// 	type: 'text',
			// 	position: 'middle',
			// 	text: "网络异常，请稍后重试"
			// })
			// 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
			if (res.code === 991 || res.code === 992) {
				// console.log(991,992)
			}
			// return Promise.reject('error')
		}else {
			return response
		}
	},
	error => {
		console.log(error,'bb')
		removeAllToken("SOURCE_URI")
		
		//  return Promise.reject(error) 
	}
)

export default service
